import { Component, OnInit, OnDestroy } from '@angular/core';
import { Assembly, AssemblyStyles, AssemblyValidators, AssemblyConfigs } from '../design/fb-design.model';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { FormRepositoryService } from './fb-repository.service';
import { ConfirmationService } from 'primeng/primeng';
import { MdlSnackbarService, MdlDialogService } from '@angular-mdl/core';
import { switchMap } from 'rxjs/operators';

@Component({
  templateUrl: './fb-repository-detail.component.html',
  styleUrls: ['./fb-repository-detail.component.scss'],
  providers: [FormRepositoryService]
})
export class FormRepositoryDetailComponent implements OnInit, OnDestroy {
  visiable: boolean = false;
  repoFormId: number;
  assemblies: Assembly[] = [];

  formName: string;
  bizs: any[] = [];
  selectedBiz: any;
  procs: any[] = [];
  selectedProc: any;
  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private mdlDialogService: MdlDialogService,
    private snackbarService: MdlSnackbarService,
    private formRepositoryService: FormRepositoryService,
    private confirmationService: ConfirmationService) {
  }

  ngOnInit() {
    this.route.paramMap.pipe(
      switchMap((params: ParamMap) => {
        this.repoFormId = +params.get('id');
        return this.formRepositoryService.loadRepoAssembliesByFormId(this.repoFormId);
      })
    ).subscribe(data => {
      let array = [];
      data.forEach(ele => {
        let temp = new Assembly(ele);
        temp.name = ele.assemblyName;
        temp.value = ele.assemblyValue;
        temp.authFlag = ele.authFlag;//是否需要授权
        temp.authCode = ele.authCode;//读写权限
        //样式
        if (ele.styleAttributes) {
          temp.attributes = new AssemblyStyles(JSON.parse(ele.styleAttributes));
          temp.attributes.x = ele['positionX'];
          temp.attributes.y = ele['positionY'];
        }
        //验证
        temp.validators = new AssemblyValidators(ele.validAttributes ? JSON.parse(ele.validAttributes) : {});
        //配置
        temp.configs = new AssemblyConfigs(ele.configAttributes ? JSON.parse(ele.configAttributes) : {});
        temp.attributes.refreshStyle();
        array.push(temp);
      });
      this.assemblies = array;

      //加载输出表单
      this.formRepositoryService.loadRepoPrintForm(this.repoFormId).subscribe(data => {
        var pdfData = atob(data.fileContent); //$.base64.
        var uint8Array = new Uint8Array(pdfData.length);
        for (var i = 0; i < pdfData.length; i++) {
          uint8Array[i] = pdfData.charCodeAt(i);
        }
        window['printPdfContent'] = { 'pdfName': data.fileName, 'pdfContent': uint8Array };
      });

      //加载业务流程
      this.formRepositoryService.loadBizProcTree().subscribe(data => this.bizs = data);
    });

  }

  ngOnDestroy() {
  }
  /**切换输入/输出表单 */
  exchange() {
    if (this.visiable) {
      $(".print-form-container").hide();
      $(".dynamic-form-container").show();
    } else {
      $(".print-form-container").show();
      $(".dynamic-form-container").hide();
    }

    this.visiable = !this.visiable;
  }
  /**从仓库移除表单 */
  removeRepo() {
    this.confirmationService.confirm({
      header: '确认',
      message: '您确定要从仓库删除这个表单吗？',
      accept: () => {
        this.formRepositoryService.deleteFromRepo(this.repoFormId).subscribe(data => {
          this.router.navigate(['/form/repository']);
          this.snackbarService.showToast("从仓库删除表单成功");
        });
      }
    });
  }
  /** 从仓库下载文书 */
  download() {
    if (!this.formName) {
      this.mdlDialogService.alert("请填写文书名称");
      return;
    }
    if (!this.selectedBiz) {
      this.mdlDialogService.alert("请选择所属业务");
      return;
    }
    if (!this.selectedProc) {
      this.mdlDialogService.alert("请选择所属流程");
      return;
    }
    this.confirmationService.confirm({
      header: '确认',
      message: '您确定要从仓库下载这个表单吗？',
      accept: () => {
        let formDef = {
          'formName': this.formName,
          'bizId': this.selectedBiz.id.split('_')[1],
          'bizName': this.selectedBiz.label,
          'procDefId': this.selectedProc.id.split('_')[1],
          'procDefName': this.selectedBiz.label
        }
        this.formRepositoryService.pullFromRepo(formDef, this.repoFormId).subscribe(data => {
          this.snackbarService.showToast("从仓库下载表单成功");
        })
      }
    });
  }

  /** 业务类型切换 */
  bizChange(event) {
    this.procs = event.value.children;
  }
}
